//
//  GamePlayer.m
//  Galaxy
//
//  Created by antl on 1/28/13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "GamePlayer.h"
#import "SimpleAudioEngine.h"
#import "ChoiceMapScene.h"
#define ROWS 10
#define ITEM_PER_ROWS  6
static CGPoint BLOCK_APPEAR_POSTION[]={
    {30 ,900},{30+53*1,900},{30+53*2,900},{30+53*3,900},{30+53*4,900},{30+53*5,900},
    
};

@implementation GamePlayer
@synthesize lits;
#pragma mark - INIT-
-(id) init
{
	if(self==[super init])
	{
        
//        enableShooting=TRUE;
//        self.isTouchEnabled = YES;
//         CCMenuItemFont* btBack=[CCMenuItemFont itemWithString:@"Back"  target:self selector:@selector(back)];
//         btBack.position=ccp(-120,220);
//         CCMenu * iMenu=[CCMenu menuWithItems:btBack,nil];
//        [self addChild:iMenu];
        
        
        
        COUNT=0;
        lbCount=[CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d",(COUNT+1)] fontName:@"Arial" fontSize:50];
        [lbCount setAnchorPoint:ccp(0,0)];
        lbCount.position=ccp(140,260);
        [self addChild:lbCount];
        [self setupInit];
        NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
        NSNumber* Map = [defaults objectForKey:CURRENT_MAP];
        int CurrentMap=[Map intValue];
        NSLog(@"current map %d",CurrentMap);
       
        [self initPuzzleWithCurrentMap:CurrentMap];
        
        id count =[CCCallFuncN actionWithTarget:self selector:@selector(CountBeginGame:)];
        id delay=[CCDelayTime actionWithDuration:1.0f];
        [self runAction:[CCSequence actions:count,delay,count,delay,count,delay,count,nil]];
        
        
        
    }
    return self;
}
-(void)CountBeginGame:(id)sender
{
    
    COUNT++;
    
    if(COUNT>3)
    {
        [lbCount removeFromParentAndCleanup:TRUE];
        [self initPlayer];
        [self schedule:@selector(update:) interval:kEnemyMoveSpeed];
        [self schedule:@selector(shootingUpdate:) interval:1/60];
    }
    else
    {
        [lbCount setString:[NSString stringWithFormat:@"%d",(COUNT)]];
    }
    
    
}
-(void)YOUWIN
{
    
}
-(void)YOULOSE
{
    
}
-(void)initPlayer
{
    /// init GunLine
    CCMenu * iMenu=[CCMenu menuWithItems:nil];
    [iMenu setAnchorPoint:ccp(0,0)];
    iMenu.position=ccp(0,0);
    [self addChild:iMenu z:4];
    
    
    for (int index=0; index<6; index++) {
        CCMenuItemImage *item=[CCMenuItemImage itemWithNormalImage:@"gun.png" selectedImage:@"gun_hover.png" target:self selector:@selector(shooting:)];
        [item setAnchorPoint:ccp(0,0)];
        item.position=ccp(index*53,20);
        item.tag=index+tagSHOOT;
        [iMenu addChild:item];
    }
    
}

-(CGPoint)getPositionByBlockTag:(int)iTag 
{
    CGPoint result=ccp(0,0);
    for (int index=0;index<[lits count]; index++) {
        CCSprite *block=[lits objectAtIndex:index];
        
        //NSLog(@"-----%d       %d-----",iTag,(block.tag-TagPiece));
        if(iTag==(block.tag-TagPiece))
        {
            return block.position;
        }
    }
    return result;
}
-(void)initDataWithCurrentMap:(int)iMap
{
    CCSprite *sprite=[CCSprite spriteWithFile:[NSString stringWithFormat:@"Iphone4HDChar%dNormal.png",iMap]];
    float	wid = sprite.contentSize.width;
	float	hgt = sprite.contentSize.height;
	float	pieceXsize = wid/(float)itemsPerRow;
	float	pieceYsize = hgt/(float)rows;
    
    
    
    float x, y;
    int tag=0;
    for (int i = 0; i < rows; i++) {
        y = i*pieceYsize;
        
        for (int j = 0; j < itemsPerRow; j++) {
            x = j*pieceXsize;
            
            CGRect blockRect = CGRectMake(x, y, pieceXsize, pieceYsize);
            /// data block
            CCSprite *block = [CCSprite spriteWithTexture:sprite.texture rect:blockRect];
            [block setAnchorPoint:ccp(0,0)];
            /// action block
            
            Block *item=[[Block alloc] init];
                    
            item.img= [CCSprite spriteWithTexture:sprite.texture rect:blockRect];
            [item setAnchorPoint:ccp(0,0)];
            item.img.position=ccp(0,-100);
            
            if (![self isSpriteTransparentWithSprite:block]) {
                block.position = ccp((x + pieceXsize/2)/*-35*/ +2*j, (hgt - y - pieceYsize/2)-2*i);
                
                //NSLog(@"++++%8.3f %8.3f++++",pieceXsize,pieceYsize);
                /// add data 
                block.tag=TagPiece+tag;
                [lits addObject:block];
                /// add action
                item.img.tag=ActionPiece+tag;
                
                [ArrActionBlock addObject:item];
                [self addChild:item.img z:3];
                
                
            }
            SAFE_RELEASE(item);
            ///[self addChild:block]; /// testing
            tag++;
        }
    }
    
    /////
    
    
    NSLog(@"lits count =%d",[lits count]);
    NSLog(@"action Peice  count =%d",[ArrActionBlock count]);
}
    


-(void)initPuzzleWithCurrentMap:(int)iMap
{
    [self initDataWithCurrentMap:iMap];
   // CGPoint P=[self getPositionByBlockTag:2+TagPiece];
   // NSLog(@"%8.3f -%8.3f",P.x,P.y);
    
}
-(void)shooting:(id)sender
{
     CCMenuItemImage *item=(CCMenuItemImage*)sender;
   // NSLog(@"%d",item.tag);
    
    CCSprite *bullet=[CCSprite spriteWithFile:[self getBulletByType:typeBullet]];
    bullet.position=ccp(item.position.x+25,item.position.y+10);
    [self addChild:bullet z:4];
    [[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"];
    [bullet runAction:[CCSequence actions:
                       [CCMoveTo actionWithDuration:kSpeedBullet position:ccp(bullet.position.x+25,480)],
                       [CCCallFuncN actionWithTarget:self selector:@selector(bulletMoveFinished:)],
                       nil]];
    
    [listBullet addObject:bullet ];
}

-(void)back
{
    [self changePageWithScene:[ChoiceMapScene node] type:FlipX];
}
-(void)dealloc
{
    [super dealloc];
    SAFE_RELEASE(listEnemy);
    SAFE_RELEASE(listBullet);
    SAFE_RELEASE(lits);
    SAFE_RELEASE(ArrActionBlock);
}
-(void)setupInit{ 
    
    typeBullet=NOMARL_BULLET;
    rows=ROWS;
    itemsPerRow=ITEM_PER_ROWS;
    lits = [[NSMutableArray alloc] init];
    ArrActionBlock = [[NSMutableArray alloc] init];
    listBullet = [[NSMutableArray alloc] init];
}



#pragma mark - UPDATE - TIMER
-(void)BlockMoveFinished:(id)sender:(Block *)tempBlock {
    
    CCSprite *sprite = (CCSprite *)sender;
	sprite.position=ccp(0,-100);
    tempBlock.available=YES;
    
}

-(void)BlockMoveBegin:(id)sender:(Block *)tempBlock  {
    
    
    tempBlock.available=NO;
}

- (void)update:(ccTime)dt {

    int random=arc4random()%[ArrActionBlock count];
    if(random>=[ArrActionBlock count]){NSLog(@"******************************"); return;}
    Block * EN  =[ ArrActionBlock objectAtIndex:random];
    if(EN!=nil&&EN.available==TRUE)
    {      
           
        int randomPosition=arc4random()%5;
        CGPoint P=BLOCK_APPEAR_POSTION[randomPosition];
        EN.img.position=P;            
        //NSLog(@"%8.3f",P.x);
        id Begin =[CCCallFuncND actionWithTarget:self selector:@selector(BlockMoveBegin::) data:EN];
        id Moving =[CCMoveTo actionWithDuration:kSpeedBullet position:ccp(P.x,-100)];
        id End    =[CCCallFuncND actionWithTarget:self selector:@selector(BlockMoveFinished::) data:EN];
        [EN.img runAction:[CCSequence actions:Begin,Moving,End,nil]];
            
    }
   
}
-(void)shootingUpdate:(ccTime)dt {
    
    NSMutableArray *ListBullet = [[NSMutableArray alloc] init];
    for (CCSprite *bullet in listBullet) {
        CGRect bulletRect = CGRectMake(bullet.position.x - (bullet.contentSize.width/2), 
                                       bullet.position.y - (bullet.contentSize.height/2), 
                                       bullet.contentSize.width, 
                                       bullet.contentSize.height);
        
        NSMutableArray *BlockDelete = [[NSMutableArray alloc] init];
        BOOL isShoot=FALSE;
        for (Block *iBlock in ArrActionBlock)
        {
            CGRect iBlockRect = CGRectMake(iBlock.img.position.x - (iBlock.img.contentSize.width/4), 
										   iBlock.img.position.y - (iBlock.img.contentSize.height/4), 
										   iBlock.img.contentSize.width/2, 
										   iBlock.img.contentSize.height/2);
            
            if (CGRectIntersectsRect(bulletRect, iBlockRect)) {
              
                 isShoot=TRUE;
                [BlockDelete addObject:iBlock];	
                
            }

        }
        
        
        for (Block *target in BlockDelete) {
            
            [target.img stopAllActions];
            [ArrActionBlock removeObject:target];
            
            
            id action2 = [CCRotateBy actionWithDuration:1.5 angle:360];
            id repeat =  [CCRepeatForever actionWithAction:action2];
            [target.img  runAction:repeat];

            //[target.img removeFromParentAndCleanup:TRUE];
           // NSLog(@"target  %d",target.img.tag-ActionPiece);
            CGPoint P=[self getPositionByBlockTag:target.img.tag-ActionPiece];
            id Moving =[CCMoveTo actionWithDuration:kSpeedImage position:P];
            id finish =[CCCallFuncN actionWithTarget:self selector:@selector(iReoderZ:) ];
            [target.img runAction:[CCSequence actions:Moving,finish,nil]];
            
            
            if([ArrActionBlock count]==0)
            {
                //[self stopAllActions];
                NSLog(@"YOU WIN");
                [self unscheduleAllSelectors];
            }
            
        }
        if ([BlockDelete count] > 0||isShoot==TRUE)
        {
            [ListBullet addObject:bullet];
        }
        SAFE_RELEASE(BlockDelete);
    
    }
    for (CCSprite *removeSprite in ListBullet) {
        [listBullet removeObject:removeSprite];
        [self removeChild:removeSprite cleanup:YES];
    }
    SAFE_RELEASE(ListBullet);
    
    
}

-(void)iReoderZ:(id)sender
{
    CCSprite *sprite = (CCSprite *)sender;
    [self reorderChild:sprite z:2];
    [sprite stopAllActions];
    [sprite setRotation:0];
}

#pragma Mark -  SHOOTING START--------
//-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    if(enableShooting==FALSE){return;}
//    enableShooting=TRUE;
//    CCSprite *bullet=[CCSprite spriteWithFile:[self getBulletByType:typeBullet]];
//    bullet.position=mySHIP.position;
//   [self addChild:bullet];
//    [[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"];
//    [bullet runAction:[CCSequence actions:
//						   [CCMoveTo actionWithDuration:kSpeedBullet position:ccp(bullet.position.x,bullet.position.y+450)],
//						   [CCCallFuncN actionWithTarget:self selector:@selector(bulletMoveFinished:)],
//						   nil]];
//    
//    [listBullet addObject:bullet];
//}
-(void)removeExposion:(id)sender
{
    AnimationClass *explosion=(AnimationClass *)sender;
    [explosion removeFromParentAndCleanup:TRUE];
}
-(void)bulletMoveFinished:(id)sender {
    
    CCSprite *sprite = (CCSprite *)sender;
	[self removeChild:sprite cleanup:YES];
    [listBullet removeObject:sprite];
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    enableShooting=FALSE;
}
#pragma Mark -  SHOOTING END--------
-(NSString*)getBulletByType:(BULLET_TYPE)type
{
    switch (type) {
        case NOMARL_BULLET:
           return  @"bullet_blue.png";
            break;
        case STRONG_BULLET:
            return  @"bullet_red.png";
            break;
        case ULTIL:
            return  @"";
            break;
        default:
            return  @"";
            break;
    }
}
@end
